package com.hushao.lims.weblims.service.impl;

import com.hushao.lims.weblims.domain.ConsumableApply;
import com.hushao.lims.weblims.domain.ConsumableInfo;
import com.hushao.lims.weblims.domain.ConsumableRepertory;
import com.hushao.lims.weblims.domain.TeacherInfo;
import com.hushao.lims.weblims.repository.ConsumableApplyRepository;
import com.hushao.lims.weblims.service.ConsumableApplyService;
import com.hushao.lims.weblims.service.ConsumableRepertoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 930588706
 * @date 18/1/24
 */
@Service
public class ConsumableApplyServiceImpl implements ConsumableApplyService {

    @Autowired
    private ConsumableApplyRepository consumableApplyRepository;
    @Autowired
    private ConsumableRepertoryService consumableRepertoryService;

    @Override
    public Page<ConsumableApply> listConsumableApplyByNameLikeAndStateLike(String consumableName, String state, Pageable pageable) {
        consumableName="%"+consumableName+"%";
        state="%"+state+"%";
        return consumableApplyRepository.findByConsumableInfo_ConsumableNameLikeAndApplyConsumableStateLike(consumableName,state,pageable);
    }

    @Override
    public List<ConsumableApply> listConsumableAndCountAndState(ConsumableInfo consumableInfo, Integer consumableCount, String state) {
        return consumableApplyRepository.findByConsumableInfoAndConsumableCountAndApplyConsumableState(consumableInfo,consumableCount,state);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ConsumableApply update(ConsumableApply consumableApply) throws Exception {
        return consumableApplyRepository.save(consumableApply);
    }

    @Override
    public void audit(Long consumableApplyId, String state, TeacherInfo teacher) throws Exception {
        ConsumableApply consumableApply=consumableApplyRepository.getOne(consumableApplyId);
        if(consumableApply==null){
            throw  new Exception("此耗材申请记录不存在！");
        }
        if(!"0".equals(consumableApply.getApplyConsumableState())){
            throw new Exception("此耗材申请信息已被审核！");
        }
        Integer count=consumableApply.getConsumableCount();
        if("1".equals(state)){
            ConsumableInfo consumableInfo=consumableApply.getConsumableInfo();
            ConsumableRepertory consumableRepertory=consumableRepertoryService.findByConsumable(consumableInfo);
            if(consumableRepertory==null||consumableRepertory.getConsumableCount()<count){
                throw new Exception("此耗材库存没有或小于申请数量,无法通过！");
            }
        }
        consumableApply.setApplyConsumableAudit(teacher);
        consumableApply.setApplyConsumableState(state);
       this.update(consumableApply);
    }
}
